<template>
  <div class="profile-view">
    <Header />
    
    <div class="profile-container">
      <div class="profile-sidebar">
        <div class="user-card">
          <div class="user-avatar">
            <el-avatar :size="80" :src="userInfo.avatar" />
          </div>
          
          <!-- 用户名显示在头像下方 -->
          <h3 class="user-name">{{ userInfo.username }}</h3>
          
          <div class="user-info">
            <p class="user-bio">{{ userInfo.bio }}</p>
            
            <div class="user-stats">
              <div class="stat-item">
                <span class="stat-number">{{ userStats.published }}</span>
                <span class="stat-label">已发布</span>
              </div>
              <div class="stat-item">
                <span class="stat-number">{{ userStats.sold }}</span>
                <span class="stat-label">已售出</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="sidebar-menu">
          <div 
            v-for="item in menuItems" 
            :key="item.key" 
            :class="['menu-item', { active: activeMenu === item.key }]"
            @click="handleMenuChange(item.key)"
          >
            <el-icon><component :is="item.icon" /></el-icon>
            <span>{{ item.label }}</span>
          </div>
        </div>
      </div>
      
      <div class="profile-content">
        <div class="content-header">
          <h2>{{ activeMenuLabel }}</h2>
        </div>
        
        <div class="content-body">
          <!-- 我发布的商品 -->
          <div v-if="activeMenu === 'published'" class="published-products">
            <div class="products-grid">
              <ProductCard 
                v-for="product in userProducts" 
                :key="product.id" 
                :product="product"
                class="profile-product-card"
              />
            </div>
            
            <div class="empty-state" v-if="userProducts.length === 0">
              <el-empty description="暂无发布的商品">
                <el-button type="primary" @click="goToPublish">
                  去发布
                </el-button>
              </el-empty>
            </div>
          </div>
          
          <!-- 我的订单 -->
          <div v-else-if="activeMenu === 'orders'" class="orders-section">
            <div v-if="userOrders.length > 0" class="orders-list">
              <OrderCard 
                v-for="order in userOrders" 
                :key="order.id" 
                :order="order"
                :show-actions="true"
                @order-updated="loadUserOrders"
                class="order-card-item"
              />
            </div>
            
            <div v-else class="empty-state">
              <el-empty description="暂无订单记录" />
            </div>
          </div>
          
          <!-- 我的收藏 -->
          <div v-else-if="activeMenu === 'favorites'" class="favorites-section">
            <el-empty description="暂无收藏商品" />
          </div>
          
          <!-- 账户设置 -->
          <div v-else-if="activeMenu === 'settings'" class="settings-section">
            <el-form :model="settingsForm" label-width="100px">
              <el-form-item label="头像">
                <el-upload
                  class="avatar-uploader"
                  :show-file-list="false"
                  :before-upload="beforeAvatarUpload"
                  :http-request="handleAvatarUpload"
                >
                  <img v-if="settingsForm.avatar" :src="settingsForm.avatar" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              
              <el-form-item label="昵称">
                <el-input v-model="settingsForm.username" />
              </el-form-item>
              
              <el-form-item label="邮箱">
                <el-input v-model="settingsForm.email" />
              </el-form-item>
              
              <el-form-item label="个人简介">
                <el-input 
                  v-model="settingsForm.bio" 
                  type="textarea" 
                  :rows="3" 
                />
              </el-form-item>
              
              <el-form-item>
                <el-button type="primary" @click="saveSettings">保存设置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    
    <Footer />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getUserInfo, updateUserInfo } from '@/api/auth.js'
import { getUserProducts } from '@/api/product.js'
import { getUserOrders } from '@/api/order.js'
import { 
  Edit, 
  Goods, 
  ShoppingCart, 
  Star, 
  Setting,
  Document,
  CollectionTag,
  Plus
} from '@element-plus/icons-vue'
import Header from '@/components/Header.vue'
import Footer from '@/components/Footer.vue'
import ProductCard from '@/components/ProductCard.vue'
import OrderCard from '@/components/OrderCard.vue'

const router = useRouter()
const activeMenu = ref('published')
const loading = ref(false)

// 用户信息
const userInfo = reactive({
  id: null,
  username: '',
  avatar: '',
  bio: '',
  email: '',
  phone: ''
})

// 用户统计
const userStats = reactive({
  published: 0,
  sold: 0,
  followers: 0
})

// 菜单项
const menuItems = [
  { key: 'published', label: '我发布的', icon: Goods },
  { key: 'orders', label: '我的订单', icon: Document },
  //{ key: 'favorites', label: '我的收藏', icon: Star },
  // { key: 'cart', label: '购物车', icon: ShoppingCart },
  { key: 'settings', label: '账户设置', icon: Setting }
]

// 设置表单
const settingsForm = reactive({
  avatar: '',
  username: '',
  email: '',
  phone: '',
  bio: ''
})

// 用户发布的商品
const userProducts = ref([])

// 用户订单
const userOrders = ref([])

// 加载用户信息
const loadUserInfo = async () => {
  try {
    loading.value = true
    const response = await getUserInfo()
    console.log('用户信息API响应:', response) // 添加调试日志
    
    if (response && response.code === 200) {
      const userData = response.data
      console.log('用户数据:', userData) // 添加调试日志
      
      // 处理头像URL - 如果是相对路径，添加基础URL
      let avatarUrl = userData.avatar || ''
      if (avatarUrl && !avatarUrl.startsWith('http') && !avatarUrl.startsWith('data:')) {
        // 这里需要根据你的后端配置添加正确的基础URL
        avatarUrl = `http://127.0.0.1:8000${avatarUrl}`
      }
      
      Object.assign(userInfo, {
        id: userData.id,
        username: userData.username || '',
        avatar: avatarUrl,
        bio: userData.bio || '',
        email: userData.email || '',
        phone: userData.phone || ''
      })
      
      // 更新用户统计信息
      if (userData.stats) {
        Object.assign(userStats, userData.stats)
      }
      
      // 更新设置表单
      Object.assign(settingsForm, {
        avatar: avatarUrl,
        username: userData.username || '',
        email: userData.email || '',
        phone: userData.phone || '',
        bio: userData.bio || ''
      })
    } else {
      console.error('获取用户信息失败:', response?.message || '未知错误')
      ElMessage.error('获取用户信息失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载用户信息失败 - 详细错误信息:', error)
    console.error('错误响应:', error.response)
    console.error('错误状态码:', error.code)
    console.error('错误消息:', error.message)
    ElMessage.error('加载用户信息失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 加载用户订单
const loadUserOrders = async () => {
  try {
    loading.value = true
    const response = await getUserOrders()
    console.log('用户订单API响应:', response) // 添加调试日志
    
    if (response && response.code === 200) {
      // 后端返回的数据结构是 { data: { list: [...], total: X, page: X, pageSize: X } }
      userOrders.value = response.data?.list || []
      console.log('用户订单列表:', userOrders.value) // 添加调试日志
    } else {
      console.error('获取用户订单失败:', response?.message || '未知错误')
      ElMessage.error('获取订单失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载用户订单失败 - 详细错误信息:', error)
    console.error('错误响应:', error.response)
    console.error('错误状态码:', error.code)
    console.error('错误消息:', error.message)
    ElMessage.error('加载订单失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 加载用户发布的商品
const loadUserProducts = async () => {
  try {
    loading.value = true
    
    // 检查token是否存在
    const token = localStorage.getItem('token')
    console.log('当前token:', token)
    
    const response = await getUserProducts()
    console.log('用户发布商品API响应:', response) // 添加调试日志
    
    if (response && response.code === 200) {
      const productList = response.data?.list || []
      console.log('用户发布商品列表:', productList) // 添加调试日志
      
      userProducts.value = productList.map(product => ({
        id: product.id,
        title: product.title || product.name,
        price: product.price,
        image: product.images && product.images.length > 0 
          ? product.images[0].image || product.images[0] 
          : '',
        description: product.description,
        category: product.category,
        status: product.status,
        publishTime: product.publishTime || product.created_at
      }))
      
      // 更新已发布商品数量统计
      userStats.published = productList.length
    } else {
      console.error('获取用户发布商品失败 - 响应结构:', response)
      console.error('错误消息:', response?.message || '未知错误')
      ElMessage.error('获取发布商品失败: ' + (response?.message || '未知错误'))
    }
  } catch (error) {
    console.error('加载用户发布商品失败 - 详细错误信息:', error)
    console.error('错误响应:', error.response)
    console.error('错误状态码:', error.code)
    console.error('错误消息:', error.message)
    console.error('错误堆栈:', error.stack)
    ElMessage.error('加载发布商品失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 订单状态处理
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待付款',
    'paid': '已付款',
    'shipped': '已发货',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || status
}

const getStatusClass = (status) => {
  const classMap = {
    'pending': 'status-pending',
    'paid': 'status-paid',
    'shipped': 'status-shipped',
    'completed': 'status-completed',
    'cancelled': 'status-cancelled'
  }
  return classMap[status] || 'status-default'
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 监听菜单切换
const handleMenuChange = (menuKey) => {
  activeMenu.value = menuKey
  
  // 当切换到订单菜单时加载订单数据
  if (menuKey === 'orders') {
    loadUserOrders()
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadUserInfo()
  loadUserProducts()
})

const activeMenuLabel = computed(() => {
  const item = menuItems.find(item => item.key === activeMenu.value)
  return item ? item.label : ''
})

const goToPublish = () => {
  router.push('/publish')
}

// 头像上传前检查
const beforeAvatarUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGOrPNG) {
    ElMessage.error('头像只能是 JPG 或 PNG 格式!')
  }
  if (!isLt2M) {
    ElMessage.error('头像大小不能超过 2MB!')
  }

  return isJPGOrPNG && isLt2M
}

// 处理头像上传
const handleAvatarUpload = async ({ file }) => {
  try {
    // 创建FormData对象用于上传文件
    const formData = new FormData()
    formData.append('avatar', file)
    
    // 使用updateUserInfo函数上传头像
    const { data } = await updateUserInfo(formData)
    
    if (data.code === 200) {
      // 更新本地头像显示，使用后端返回的头像URL
      settingsForm.avatar = data.data.avatar
      userInfo.avatar = data.data.avatar
      
      ElMessage.success('头像上传成功!')
    }
  } catch (error) {
    console.error('头像上传失败:', error)
    ElMessage.error('头像上传失败')
  }
}

// 保存设置
const saveSettings = async () => {
  try {
    loading.value = true
    const updateData = {
      username: settingsForm.username,
      email: settingsForm.email,
      phone: settingsForm.phone,
      bio: settingsForm.bio
    }
    
    const { data } = await updateUserInfo(updateData)
    if (data.code === 200) {
      // 更新本地用户信息
      Object.assign(userInfo, {
        username: settingsForm.username,
        email: settingsForm.email,
        phone: settingsForm.phone,
        bio: settingsForm.bio
      })
      
      ElMessage.success('设置保存成功!')
    }
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error('保存设置失败')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.profile-view {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.profile-container {
  flex: 1;
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 30px;
}

.profile-sidebar {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-card {
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  text-align: center;
}

.user-avatar {
  margin-bottom: 16px;
}

.user-name {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 18px;
}

.user-bio {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-number {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.sidebar-menu {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 16px 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  gap: 12px;
}

.menu-item:hover {
  background-color: #f5f7fa;
}

.menu-item.active {
  background-color: #ecf5ff;
  color: #409EFF;
  border-right: 3px solid #409EFF;
}

.profile-content {
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.content-header {
  padding: 24px;
  border-bottom: 1px solid #eee;
}

.content-header h2 {
  margin: 0;
  color: #333;
}

.content-body {
  padding: 24px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}

.profile-product-card {
  transform: scale(0.95);
}

.empty-state {
  text-align: center;
  padding: 60px 0;
}

.settings-section {
  max-width: 500px;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100px;
  height: 100px;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}

/* 订单列表样式 */
.orders-section {
  padding: 0;
}

.order-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  margin-bottom: 16px;
  background: #fff;
  transition: box-shadow 0.3s;
}

.order-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.order-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.order-number {
  font-weight: 600;
  color: #333;
}

.order-date {
  font-size: 12px;
  color: #999;
}

.order-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
}

.status-pending {
  background: #fff7e6;
  color: #fa8c16;
}

.status-paid {
  background: #f6ffed;
  color: #52c41a;
}

.status-shipped {
  background: #e6f7ff;
  color: #1890ff;
}

.status-completed {
  background: #f6ffed;
  color: #52c41a;
}

.status-cancelled {
  background: #fff2f0;
  color: #ff4d4f;
}

.status-default {
  background: #f9f9f9;
  color: #666;
}

.order-body {
  padding: 16px;
}

.order-items {
  margin-bottom: 12px;
}

.order-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.item-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 12px;
}

.item-info {
  flex: 1;
}

.item-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.item-price {
  color: #ff4d4f;
  font-weight: 600;
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
}

.order-total {
  font-size: 16px;
  font-weight: 600;
  color: #ff4d4f;
}

.order-actions {
  display: flex;
  gap: 8px;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 0;
}

.empty-orders {
  text-align: center;
  padding: 60px 0;
  color: #999;
}
</style>